/*
 * DRB.java
 *
 * Created on October 2, 2007, 2:23 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package drb;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 *
 * @author Asger
 */
public class DRB extends PromptingCommand {
    
    private ApplyScheduleCommand applyScheduleCmd = new ApplyScheduleCommand();
    private TicketCommandGroup ticketCmd = new TicketCommandGroup(input);
    private BookingCommandGroup bookingCmd = new BookingCommandGroup(input);
    private AdminCommandGroup adminCmd = new AdminCommandGroup(input);
    
    /**
     * Creates a new instance of DRB
     */
    public DRB(BufferedReader input) {
        super(input);
    }
    
    public void setConnection(Connection connection) {
        this.connection = connection;
        applyScheduleCmd.setConnection(connection);
        ticketCmd.setConnection(connection);
        bookingCmd.setConnection(connection);
        adminCmd.setConnection(connection);
    }
    
    private void init()
    {
        System.out.println("------------------------------");
        System.out.println(" DRB Client");
        System.out.println("------------------------------");
        
        // Connect to the database
        System.out.print("Connecting to database...");
        try {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            
            // Read the configuration
            Properties config = new Properties();
            config.load(new FileReader("config/database.properties"));
            
            String hostname = config.getProperty("database.host");
            String username = config.getProperty("database.username");
            String password = config.getProperty("database.password");
            String database = config.getProperty("database.name");
            
            String url = "jdbc:mysql://" + hostname + ":3306/" + database
                + "?user=" + username + "&password=" + password;
            
            connection = DriverManager.getConnection(url);
            
            if (connection != null)
                System.out.println("OK");
        }
        catch (SQLException e) {
            System.err.println("FAIL!");
            System.err.println(e);
        }
        catch (IOException e) {
            System.err.println("FAIL!");
            System.err.println(e);
        }
        setConnection(connection);
    }
    
    public void printHelp() {
        System.out.println("-------------------------------");
        System.out.println(" tickets          | Find connections and issue new tickets");
        System.out.println(" booking          | Book seats for existing tickets");
        System.out.println(" admin            | Scheduling and statistics");
        System.out.println(" apply-scheudle   | Applies scheduled connections");
        System.out.println(" cancel           | Special: Cancels the current command");
        System.out.println(" exit             | Special: Exits the program");
        System.out.println("-------------------------------");
    }
    
    private void doom() throws SQLException {
        long start = 13*ONE_HOUR;
        long end = 15*ONE_HOUR;
        long plus = 5*ONE_HOUR;
        String sql = "SELECT * FROM schedule WHERE departure>="+start+" AND arrival<="+end;
        ResultSet result = connection.createStatement().executeQuery(sql);
        while (result.next()) {
            long departure = result.getLong("departure") + plus;
            long arrival = result.getLong("arrival") + plus;
            String from = result.getString("from_name");
            String to = result.getString("to_name");
            int numWagons = result.getInt("num_wagons");
            String weekDays = result.getString("week_days");
            int ecoPrice = result.getInt("eco_price");
            int fcPrice = result.getInt("fc_price");
            String wagonType = "B";
            sql = "INSERT INTO schedule (departure, arrival, from_name, to_name, num_wagons, week_days, eco_price, fc_price, wagon_type) VALUES " +
                    "("+departure+", "+arrival+", '"+escapeSQL(from)+"', '"+escapeSQL(to)+"', "+numWagons+", '"+weekDays+"', "+ecoPrice+", "+fcPrice+", '"+wagonType+"')";
            connection.createStatement().execute(sql);
        }
    }
    
    public void execute()
    {
        init();
        
        try
        {
            applyScheduleCmd.execute();
            printHelp();
            while (true) {
                
                try {
                    String cmd = getInput();
                    
                    if (cmd.equals("tickets")) {
                        ticketCmd.execute();
                        printHelp();
                    } else if (cmd.equals("booking")) {
                        bookingCmd.execute();
                        printHelp();
                    } else if (cmd.equals("admin")) {
                        adminCmd.execute();
                        printHelp();
                    } else if (cmd.equals("apply-schedule")) {
                        applyScheduleCmd.execute();
                    } else if (cmd.equals("help")) {
                        printHelp();
                    } else {
                        System.err.println("Unknown command. Type 'help' for a list of commands.");
                    }
                } catch (CancelCommandException ex) {
                    printHelp();
                }
            }
        } catch (ExitProgramException ex) {
            // Just exit the program normally..
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        DRB main = new DRB(new BufferedReader(new InputStreamReader(System.in)));
        main.execute();
    }
    
}














